import React, { useState, useEffect, useRef, useMemo, memo } from "react";
import "./Todolist.css";

// 自定义 Hook useId，为每个待办事项生成唯一的ID
function useId() {
  const idRef = useRef(0);
  return () => {
    idRef.current += 1;
    return `id-${idRef.current}`;
  };
}
// 使用 memo 包裹 TodoItem 组件，避免不必要的重新渲染
const TodoItem = memo(({ todo, onToggle, onDelete }) => {
  return (
    <li key={todo.id} className={todo.completed ? "completed" : "li"}>
      <div className="left">
        <input
          type="checkbox"
          checked={todo.completed}
          onChange={(e) => onToggle(todo.id)}
        />
        {todo.text}
      </div>
      <div className="right">
        <button onClick={() => onDelete(todo.id)}>删除</button>
      </div>
    </li>
  );
});

const Todolist = () => {
  const [todos, setTodos] = useState([]);
  const [cls, setCls] = useState("all");
  const getId = useId(); // 生成唯一ID的函数
  const inputRef = useRef(null); // 保持对输入框的引用

  useEffect(() => {
    // 从LocalStorage加载数据
    const savedTodos = localStorage.getItem("todos");
    if (savedTodos) {
      setTodos(JSON.parse(savedTodos));
    }
  }, []);

  useEffect(() => {
    // 每当todos更新时，同步到LocalStorage
    localStorage.setItem("todos", JSON.stringify(todos));
  }, [todos]);

  const ChangeTab = (tab) => {
    setCls(tab);
  };

  const AddList = (e) => {
    if (e.key === "Enter" && e.target.value.trim()) {
      setTodos([
        ...todos,
        { id: getId(), text: e.target.value.trim(), completed: false },
      ]);
      e.target.value = "";
      inputRef.current.focus(); // 重新聚焦输入框
    }
  };

  const deleteTodo = (id) => {
    setTodos(todos.filter((todo) => todo.id !== id));
  };

  const toggleTodo = (id) => {
    setTodos(
      todos.map((todo) =>
        todo.id === id ? { ...todo, completed: !todo.completed } : todo
      )
    );
  };

  const filteredTodos = useMemo(() => {
    return todos.filter((todo) => {
      if (cls === "all") return true;
      if (cls === "no") return !todo.completed;
      if (cls === "yes") return todo.completed;
      return false;
    });
  }, [todos, cls]);

  const tabs = [
    { id: "1", clsNe: "all", text: "所有任务" },
    { id: "2", clsNe: "no", text: "未完成的任务" },
    { id: "3", clsNe: "yes", text: "已完成的任务" },
  ];

  return (
    <div className="background">
      <div className="bigbox">
        <div className="head">任务计划列表</div>
        <div className="nav">
          <h1>任务列表</h1>
          <div className="tabList">
            {tabs.map((tab) => (
              <div
                key={tab.id}
                className={`tab ${cls === tab.clsNe ? "active" : ""}`}
                onClick={() => ChangeTab(tab.clsNe)}
              >
                {tab.text}
              </div>
            ))}
          </div>
        </div>
        <div className="input">
          <input
            type="text"
            placeholder="请输入，提示：点击回车添加任务"
            onKeyUp={AddList}
            ref={inputRef}
          />
        </div>
        <div className="list">
          <ul>
            {filteredTodos.map((todo) => (
              <TodoItem
                key={todo.id}
                todo={todo}
                onToggle={toggleTodo}
                onDelete={deleteTodo}
              />
            ))}
          </ul>
        </div>
      </div>
    </div>
  );
};

export default Todolist;
